﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace VFTray
{
	abstract class FunHelper
    {
		internal static IntPtr ImageDataRevers(Image img)
		{

			Bitmap src = (Bitmap)img;
			BitmapData bd = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadOnly, src.PixelFormat);
			//int to_size = bd.Stride * src.Height;
			int to_size = src.Width * src.Height;
			IntPtr pdata = Marshal.UnsafeAddrOfPinnedArrayElement(new byte[to_size], 0);
			for (int r = 0; r < src.Height; r++)
			{
				ImageUtility.ImageHelper.CopyMemory(pdata + r * src.Width, bd.Scan0 + (r) * bd.Stride, src.Width);
			}
			src.UnlockBits(bd);
			
			return pdata;
		}

		internal static Bitmap Crop(Bitmap src, Rectangle rect)
		{
			Bitmap bmp = new Bitmap(rect.Width, rect.Height, src.PixelFormat);
			if (bmp.PixelFormat == PixelFormat.Format8bppIndexed)
				bmp.Palette = ImageUtility.ImageHelper.CreateGrayPalette();

			BitmapData bd_t = bmp.LockBits(new Rectangle(0, 0, rect.Width, rect.Height), ImageLockMode.ReadWrite, src.PixelFormat);

			BitmapData bd_s = src.LockBits(rect, ImageLockMode.ReadOnly, src.PixelFormat);

			for (int r = 0; r < rect.Height; r++)
			{
				ImageUtility.ImageHelper.CopyMemory(bd_t.Scan0 + r * bd_t.Stride, bd_s.Scan0 + r * bd_s.Stride, bd_t.Stride);
			}

			src.UnlockBits(bd_s);
			bmp.UnlockBits(bd_t);
			return bmp;
		}

		internal static void UpdateStatusVisibleBackColorGreenYellow(bool visible, bool connected, ToolStripStatusLabel tss)
		{
			if (visible && tss.Visible == false)
				tss.Visible = visible;
			else if (visible == false)
			{
				if (tss.Visible) 
					tss.Visible = false;
				return;
			}
			if (connected && tss.BackColor != Color.Green)
			{
				tss.BackColor = Color.Green;
				tss.ForeColor = Color.White;
			}
			else if (connected == false && tss.BackColor != Color.Yellow)
			{
				tss.BackColor = Color.Yellow;
				tss.ForeColor = SystemColors.ControlText;
			}
		}
	}
}
